package com.token;

import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.apache.shiro.mgt.SecurityManager;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {


    @Autowired
    private LoginRealm loginRealm;

    /**
     * 配置安全管理器，那种类型的管理器
     * @return
     */
    @Bean
    public DefaultWebSecurityManager securityManager(){
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        /*
         * 关闭shiro自带的session，详情见文档
         * http://shiro.apache.org/session-management.html#SessionManagement-StatelessApplications%28Sessionless%29
         */

        DefaultSubjectDAO subjectDAO=new DefaultSubjectDAO();
        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator=new DefaultSessionStorageEvaluator();
        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);

        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);

        securityManager.setSubjectDAO(subjectDAO);
        //设置自定义realm
        securityManager.setRealm(loginRealm);
        return securityManager;

    }

    /**
     * 配置拦截器
     * 设置过滤器，将自定义的Filter加入
     * @param securityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean factory(SecurityManager securityManager){
        ShiroFilterFactoryBean filterFactoryBean=new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(securityManager);
        Map filterMap=new HashMap();
        filterFactoryBean.setFilters(filterMap);

        //设置无权限时时跳转的url
        Map<String,String> filterRuleMap=new HashMap();
        //访问/login和unauthorized 不经过过滤器

        //设置我们自定义的JWT过滤器
        filterMap.put("jwt",new JWTFilter());

        //不登录就能访问到这里   这个就是放行  不需要权限   401就是权限不够
        filterRuleMap.put("/api2/**","anon");
        filterRuleMap.put("/api/login","anon");
        filterRuleMap.put("/images/**","anon");


        //必须登录才可以访问这里
        filterRuleMap.put("/**","jwt,authc");

        //访问/unauthorized/** 不通过JWTFilter
        filterFactoryBean.setFilterChainDefinitionMap(filterRuleMap);
        return filterFactoryBean;


    }



}
